#!/bin/bash

# SSL证书配置脚本
set -e

DOMAIN=${1:-"your-domain.com"}
EMAIL=${2:-"admin@example.com"}

echo "为域名 $DOMAIN 配置SSL证书..."

# 检查是否安装了certbot
if ! command -v certbot &> /dev/null; then
    echo "安装certbot..."
    apt-get update
    apt-get install -y certbot python3-certbot-nginx
fi

# 停止nginx容器以释放80端口
echo "停止nginx容器..."
docker-compose stop nginx

# 获取Let's Encrypt证书
echo "获取SSL证书..."
certbot certonly --standalone \
    --email $EMAIL \
    --agree-tos \
    --no-eff-email \
    -d $DOMAIN \
    -d www.$DOMAIN \
    -d api.$DOMAIN

# 复制证书到nginx目录
echo "复制证书文件..."
mkdir -p nginx/ssl
cp /etc/letsencrypt/live/$DOMAIN/fullchain.pem nginx/ssl/$DOMAIN.crt
cp /etc/letsencrypt/live/$DOMAIN/privkey.pem nginx/ssl/$DOMAIN.key

# 更新nginx配置中的域名
echo "更新nginx配置..."
sed -i "s/your-domain.com/$DOMAIN/g" nginx/conf.d/default.conf

# 重启nginx容器
echo "重启nginx容器..."
docker-compose up -d nginx

# 设置证书自动续期
echo "设置证书自动续期..."
(crontab -l 2>/dev/null; echo "0 12 * * * /usr/bin/certbot renew --quiet --deploy-hook 'docker-compose restart nginx'") | crontab -

echo "SSL证书配置完成！"
echo "证书文件位置: nginx/ssl/$DOMAIN.crt"
echo "私钥文件位置: nginx/ssl/$DOMAIN.key"
echo "证书将在到期前自动续期"